import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_chat_ui/pages/agent_web_view_page/agent_web_view_page.dart';
import 'package:flutter_chat_ui/pages/chat_room_controller.dart';
import 'package:flutter_chat_ui/pages/txh_about_school_goods/goods_list_page.dart';
import 'package:flutter_chat_ui/pages/txh_about_school_goods/login_page.dart';
import 'package:flutter_chat_ui/utils/getx_update_keys.dart';
import 'package:flutter_chat_ui/utils/utils.dart';
import 'package:flutter_chat_ui/views/chat_app_bar_title_view.dart';
import 'package:flutter_chat_ui/views/chat_bottom_widgets/chat_bottom_view.dart';
import 'package:flutter_chat_ui/views/chat_element_other.dart';
import 'package:flutter_chat_ui/views/chat_element_self.dart';
import 'package:flutter_chat_ui/views/chat_element_welcome.dart';
import 'package:get/get.dart';

///
/// 聊天室主体页面
///
class ChatRoomBodyPage extends StatefulWidget {
  /// 点击左侧菜单
  final VoidCallback? onLeftMenuClick;

  const ChatRoomBodyPage({
    super.key,
    this.onLeftMenuClick,
  });

  @override
  State<ChatRoomBodyPage> createState() => _ChatRoomBodyPageState();
}

class _ChatRoomBodyPageState extends State<ChatRoomBodyPage> {
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    // 监听滚动事件
    _scrollController.addListener(() {
      if (_scrollController.position.userScrollDirection != ScrollDirection.idle) {
        ChatRoomController.to.isUserDragging = true;
      } else {
        ChatRoomController.to.isUserDragging = false;
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true, // 会自动调整布局，以避免键盘遮住内容
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const ChatAppBarTitleView(),
        leading: IconButton(
          icon: const Icon(Icons.menu),
          onPressed: widget.onLeftMenuClick,
        ),
        actions: [
          // TextButton(
          //   // onPressed: () => Get.to(() => const AsrMainPage()),
          //   onPressed: () => print("暂停使用"),
          //   child: const Text(
          //     '识别',
          //     style: TextStyle(
          //       fontSize: 16,
          //       color: Colors.red,
          //       fontWeight: FontWeight.bold,
          //     ),
          //   ),
          // ),
          TextButton(
            onPressed: () => Get.to(() => const GoodsListPage()),
            child: const Text(
              '商品',
              style: TextStyle(
                fontSize: 16,
                color: Colors.red,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          TextButton(
            // onPressed: () => Get.to(() => const GoodsListPage()),
            onPressed: () => Get.to(() => const LoginPage()),
            child: const Text(
              '登录',
              style: TextStyle(
                fontSize: 16,
                color: Colors.red,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),

          /// 加载智能体web
          TextButton(
            onPressed: () async {
              Get.to(() => const AgentWebViewPage(url: "http://192.168.2.29:8080/"));
            },
            child: const Text(
              '客服',
              style: TextStyle(
                fontSize: 16,
                color: Colors.red,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
      backgroundColor: const Color(0xfff3f3f3),
      body: Center(
        child: Flex(
          direction: Axis.vertical,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Stack(
                children: [
                  ScrollConfiguration(
                    behavior: const ScrollBehavior().copyWith(scrollbars: false),
                    // GetBuilder响应流式输出
                    child: GetBuilder<ChatRoomController>(
                        id: GetxUpdateKeys.chatListId,
                        builder: (controller) {
                          if (controller.chatMessages.length != 1 && controller.isStream) {
                            WidgetsBinding.instance.addPostFrameCallback((_) {
                              Future.delayed(const Duration(milliseconds: 100),
                                  () => _scrollToBottom(ChatRoomController.to.isUserDragging));
                            });
                          }

                          return ListView.builder(
                            key: const PageStorageKey('chat_list'), // 添加唯一key
                            controller: _scrollController,
                            itemCount: controller.chatMessages.length,
                            padding: const EdgeInsets.only(bottom: 80),
                            shrinkWrap: true,
                            reverse: controller.chatMessages.length != 1 ? true : false,
                            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
                            itemBuilder: (context, index) {
                              String type = controller.chatMessages[index].event;

                              if (type == MessageEventType.welcome.event) {
                                // 欢迎消息组件
                                return ChatElementWelcome(
                                  openingRemarksData: controller.chatMessages[index].openingRemarksData,
                                );
                              } else if (type == MessageEventType.master.event) {
                                // 主人消息组件
                                return ChatElementSelf(
                                  chatMessage: controller.chatMessages[index],
                                );
                              } else if (type == MessageEventType.robot.event) {
                                // 机器人消息组件
                                return ChatElementOther(
                                  chatMessage: controller.chatMessages[index],
                                );
                              }
                              return const SizedBox();
                            },
                          );
                        }),
                  ),
                  // 滚动到底部
                  // AnimatedPositioned(
                  //   ...
                  // ),
                ],
              ),
            ),

            /// 输入框
            ChatBottomView(
              onKeyboardStateChanged: (value) async {
                if (value != 0) {
                  // 当键盘弹出时，滚动到列表底部
                  _scrollToBottom(false);
                }
              },
              onChange: (value) => ChatRoomController.to.isTextEmpty.value = value.isEmpty,
              onSendMessage: (query) => ChatRoomController.to.sendMessage(
                query,
                conversationId: Utils.lastConversationId ?? '',
              ),
              onStopResponse: () => ChatRoomController.to.stopRobotResponse(),
            ),
          ],
        ),
      ),
    );
  }

  ///
  /// 内容滚动到底部
  ///
  void _scrollToBottom(bool userDragging) {
    if (_scrollController.hasClients && !userDragging) {
      _scrollController.animateTo(
        // _scrollController.position.maxScrollExtent,
        0,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }
}
